import { BaseEnvMirror, type EnvMirrorOptions } from "@/modules/dev-env/mirror/mirror.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import { MirrorDataFilter } from "@/modules/dev-env/mirror/filter.ts";
import type { PythonMirrorIndex, PythonVersionInfo } from "@/modules/dev-env/python/types.ts";
import type { DefaultOptionType } from "ant-design-vue/es/vc-select/Select";
import semver from "semver";

/**
 * 版本类型过滤器
 */
class PythonCompanyFilter extends MirrorDataFilter<string> {
  constructor() {
    super("版本类型", "PythonCore");
  }

  protected getDataSource0(): Promise<DefaultOptionType[]> {
    return Promise.resolve([
      { value: "PythonCore" },
      { value: "PythonEmbed" },
      { value: "PythonTest" },
      // ...
    ]);
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.edition === this.value);
  }
}

/**
 * 版本过滤器
 */
class PythonVersionFilter extends MirrorDataFilter {
  constructor() {
    super("Python版本");
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.version1 === this.value);
  }
}

/**
 * 位数过滤器
 */
class PythonBitFilter extends MirrorDataFilter<number> {
  constructor() {
    super("位数", 64);

    this.selectProps = { allowClear: true };
  }

  protected getDataSource0(): Promise<DefaultOptionType[]> {
    return Promise.resolve([
      { value: 64, label: "64位" },
      { value: 32, label: "32位" },
    ]);
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.bitness === this.value);
  }
}

export abstract class PythonEnvMirror extends BaseEnvMirror {
  private readonly _companyFilter = new PythonCompanyFilter();
  private readonly _versionFilter = new PythonVersionFilter();

  /**
   * Python大版本: 3.14, 3.13, 3.12...之类
   * @private
   */
  private readonly _pythonVersionSet = new Set<string>();

  protected constructor(options: EnvMirrorOptions) {
    super(options);
    this.unzipToVersionDir = true;
  }

  protected getFilters0(): MirrorDataFilter[] {
    return [this._companyFilter, this._versionFilter, new PythonBitFilter()];
  }

  async getDownloadList(query: Record<string, any>): Promise<ToolInstallVersionItem[]> {
    this._pythonVersionSet.clear();
    const versionList = await this._getVersions0(`${this.url}/index-windows.json`);

    const pythonVersions = [...this._pythonVersionSet];
    pythonVersions.sort((a, b) => semver.compare(b + ".0", a + ".0"));
    this._versionFilter.setDataSource(pythonVersions.map(it => ({ value: it })));
    this._versionFilter.value = pythonVersions[0];

    return versionList;
  }

  private async _getVersions0(indexUrl: string): Promise<ToolInstallVersionItem[]> {
    const resp = await native.http.getJson<PythonMirrorIndex>(indexUrl);
    const versions: PythonVersionInfo[] = [];
    const isArm = native.process.arch === "arm64";
    for (const it of resp.data.versions) {
      if (isArm) {
        if (it.tag.endsWith("arm64")) {
          versions.push(it);
        }
        continue;
      }

      if (!it.tag.endsWith("arm64")) {
        versions.push(it);
      }
    }

    // console.log(versions);

    const versionList = versions.map<ToolInstallVersionItem>(it => {
      const sortVersion = it["sort-version"];

      // 获取大版本
      const [major, minor] = sortVersion.split(".");
      const version1 = major + "." + minor;
      this._pythonVersionSet.add(version1);

      const bitness = it.id.endsWith("-64") ? 64 : 32;
      const installPath = this.getItemInstallPath(it, bitness);
      // console.log(it, installDir);

      return {
        id: `${it.id}/${sortVersion}`, // 已数据ID和分类拼接作为ID,防止ID重复
        name: it["display-name"],
        version: sortVersion,
        url: this.getDownloadUrl(it),
        bitness: bitness,
        edition: it.company,
        version1: version1,
        installPath: installPath,
        extraToTempdir: it.url.endsWith(".nupkg"), // .nupkg文件解压到临时目录
        tag: it.tag,
      };
    });

    if (resp.data.next) {
      const nextVersionList = await this._getVersions0(`${this.url}/${resp.data.next}`);
      versionList.push(...nextVersionList);
    }

    return versionList;
  }

  protected getDownloadUrl(info: PythonVersionInfo): string {
    return info.url;
  }

  private getItemInstallPath(info: PythonVersionInfo, bitness: number): string {
    const sortVersion = info["sort-version"];
    // 测试版本号 a1,a2,b1,b2,...
    let bversion = sortVersion.match(/[a-zA-Z]\d+$/)?.[0];
    // 正式版本号: 3.11.9
    const version = bversion ? sortVersion.slice(0, sortVersion.length - bversion.length) : sortVersion;
    const name = info["display-name"];
    // 是否是free-threaded版本
    const isFreeThreaded = name.includes("free-threaded") || name.includes("freethreaded");
    if (isFreeThreaded) {
      bversion = bversion ? bversion + "t" : "t";
    }
    return [info.company.toLowerCase(), version, bversion, "x" + bitness].filter(it => !!it).join("-");
  }
}

/**
 * npmmirror.com镜像
 */
export class PythonNpmMirror extends PythonEnvMirror {
  /**
   * 官网下载地址
   * @private
   */
  private readonly _officialUrl = "https://www.python.org/ftp/python";

  constructor() {
    super({
      id: "python.npmmirror",
      name: "npmmirror.com",
      url: "https://registry.npmmirror.com/-/binary/python",
      website: "https://npmmirror.com/",
    });
  }

  protected getDownloadUrl(info: PythonVersionInfo): string {
    // 将官网地址替换为镜像地址
    return info.url.replace(this._officialUrl, this.url);
  }
}

/**
 * 官网镜像
 */
export class PythonOfficialMirror extends PythonEnvMirror {
  constructor() {
    super({
      id: "python.official",
      name: "python.org",
      url: "https://www.python.org/ftp/python",
      website: "https://www.python.org/",
    });
  }
}
